﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CNFProblem.CNF
{
    public class LiteralAlternative
    {
        private int[] _variables;    //id zmiennej w literale
        private bool[] _isNeg;       //true jesli zmienna jest zanegowana w literale

        public LiteralAlternative(int n)
        {
            _variables = new int[n];
            _isNeg = new bool[n];
        }

        public void SetId(int i, int id)
        {
            _variables[i] = id;
        }

        public void SetNeg(int i, bool isNeg)
        {
            _isNeg[i] = isNeg;
        }

        public bool GetNeg(int i)
        {
            return _isNeg[i];
        }

        public int GetId(int i)
        {
            return _variables[i];
        }

        public bool HasId(int id)
        {
            return _variables.Contains(id);
        }

        public void MadeIdFirst(int id)
        {
            if (!HasId(id)) return;
            int index = Array.IndexOf(_variables, id);
            if (index != 0)
            {
                int intTmp = _variables[0];
                _variables[0] = _variables[index];
                _variables[index] = intTmp;
                bool boolTmp = _isNeg[0];
                _isNeg[0] = _isNeg[index];
                _isNeg[index] = boolTmp;
            }
        }

        public bool IsIdNegated(int id)
        {
            for (int i = 0; i < _variables.Length; ++i)
            {
                if (_variables[i] == id && _isNeg[i])
                    return true;
            }
            return false;
        }

        /// <summary>
        /// It is not the same as !IsIdNegated as one alternative may contains same symbol both negated and notnegated
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool IsIdNotNegated(int id)
        {
            for (int i = 0; i < _variables.Length; ++i)
            {
                if (_variables[i] == id && !_isNeg[i])
                    return true;
            }
            return false;
        }

        public int GetLenght()
        {
            return _variables.Length;
        }

        public bool GetValue(Dictionary<int, bool> values)
        {
            bool v = false;
            for (int i = 0; i < _variables.Length && !v; i++)
            {
                v |= values[_variables[i]] ^ _isNeg[i];
            }
            return v;
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < _variables.Length; i++)
            {
                sb.Append( (_isNeg[i] ? "~" : "") + ":" + _variables[i] + " v ");
            }
            return sb.ToString();
        }
    }
}
